package com.tal.pad.javabase.utils;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Container <T>{

    private LinkedList<T> list = new LinkedList<>();

    private int count ;

    private ReentrantLock lock = new ReentrantLock();

    private final Condition consumer = lock.newCondition();
    private final Condition producer = lock.newCondition();

    public void add(T t){
        try{
            lock.lock();
            while(list.size()==count){
                wait();
            }
            list.add(t);
            count++;
            producer.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public T get(){
        T t;
        try{
            lock.lock();
            while(list.isEmpty()){
                wait();
            }
            count--;
            t= list.pop();
            consumer.signalAll();
            return t;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

}
